package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"xinhua_bookstore/cache"
	"xinhua_bookstore/models"
)

type CollectController struct {
	beego.Controller
}

func (c *CollectController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Collect{}).Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size

	var bookId []interface{}
	UserId, _ := c.GetInt("user_id")
	models.DB.Model(models.Collect{}).Select("book_id").Where("user_id=?", UserId).Find(&bookId)

	var books []models.Book
	cacheData := cache.Rdb.Get(cache.Ctx, "books_list").Val()
	if cacheData == "" {
		models.DB.Where("id in (?)", bookId).Offset(offset).Limit(size).Find(&books)
		jsonData, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, "books._list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &books)
	}
	c.Data["json"] = map[string]interface{}{
		"code":  200,
		"msg":   "展示成功",
		"data":  &books,
		"Size":  size,
		"Page":  page,
		"Count": count,
		"Sum":   sum,
	}
	c.ServeJSON()
	return
}
func (c *CollectController) Del() {
	id, _ := c.GetInt("id")
	var collect models.Collect
	models.DB.Where("id=?", id).Find(&collect)
	if collect.Sex == "已完成交易" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "已完成交易禁止删除",
		}
		c.ServeJSON()
		return
	}
	collect.ID = uint(id)
	err := c.Del
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
